<template>
    <div class="h-screen bg-gradient-to-b from-blue-50 to-white flex flex-col overflow-hidden">
        <!-- 主内容 -->
        <div class="flex-1 flex items-center justify-center overflow-auto p-4 md:p-6">
            <Loading v-model:show="isDetecting" description="正在检测...">
                <div class="flex flex-col md:flex-row gap-6 max-w-7xl mx-auto">
                    <!-- 图片上传区域 -->
                    <div class="w-full bg-white rounded-md shadow-lg p-6 mb-6">
                        <h3 class="text-xl mb-4">
                            上传图片
                        </h3>
                        <!-- 拖拽上传区域 -->
                        <div class="border-2 border-gray-300 hover:border-blue-500 p-10 sm:p-20 min-h-[200px] flex flex-col items-center justify-center text-center cursor-pointer rounded-md mb-6 bg-gray-50 hover:bg-blue-50 transition-all duration-300"
                            @drop="handleDrop" @dragover.prevent @dragenter.prevent @click="triggerFileInput">
                            <!-- 上传前显示 -->
                            <div v-if="!imagePreview" class="flex flex-col items-center">
                                <h4 class="text-xl font-medium text-gray-700 mb-2">点击或拖拽图片到此处上传</h4>
                                <p class="text-gray-500 mb-4 max-w-md">支持 JPG、PNG、BMP 等常见图片格式，文件大小不超过 5MB</p>
                                <input type="file" accept="image/*" class="hidden" id="fileInput"
                                    @change="handleFileChange">
                            </div>
                            <!-- 上传后显示预览 -->
                            <div v-else class="w-full">
                                <img :src="imagePreview" alt="图片预览"
                                    class="max-h-[200px] max-w-full mx-auto rounded-md shadow-sm mb-4 cursor-pointer hover:opacity-80 transition-opacity duration-200"
                                    @click="previewImage">
                                <p class="text-green-600 text-sm">图片已成功上传，可以点击图片进行预览或重新上传</p>
                            </div>
                        </div>
                        <!-- 操作按钮区域 -->
                        <div class="flex justify-center gap-4 mb-4">
                            <!-- 重新上传按钮 -->
                            <button @click="showReUploadDialog = true" :disabled="!imagePreview || isDetecting"
                                class="bg-yellow-500 hover:bg-yellow-600 text-white font-bold px-6 py-3 rounded-md transition-colors duration-300 disabled:bg-gray-300 disabled:cursor-not-allowed">
                                重新上传
                            </button>
                            <!-- 检测按钮 -->
                            <button @click="showDetectionDialog = true" :disabled="!imagePreview || isDetecting"
                                class="bg-blue-600 hover:bg-blue-700 text-white font-bold px-8 py-3 rounded-md transition-colors duration-300 disabled:bg-gray-300 disabled:cursor-not-allowed">
                                {{ isDetecting ? '检测中' : '开始检测' }}
                            </button>
                            <button @click="backhome" :disabled="isDetecting"
                                class="bg-red-500 hover:bg-red-600 text-white font-bold px-6 py-3 rounded-md transition-colors duration-300 disabled:bg-gray-300 disabled:cursor-not-allowed">
                                返回首页
                            </button>
                        </div>
                    </div>
                </div>
            </Loading>
        </div>
        <!-- 重新上传确认弹窗 -->
        <Dialog v-model:show="showReUploadDialog" title="确认重新上传" message="您确定要重新上传图片吗？当前图片将被覆盖。"
            @confirm="reUploadImage" />
        <!-- 开始检测确认弹窗 -->
        <Dialog v-model:show="showDetectionDialog" title="确认开始检测" message="您确定要开始检测当前图片吗？" @confirm="startDetection" />
        <!-- 关键功能：页面级 Snackbar 组件实例 -->
        <Snackbar v-model:show="snackShow" :type="snackType" position="top" :duration="2000" :content="snackContent" />
    </div>
</template>

<script>
import Dialog from '../../components/dialog.vue';
import Loading from '../../components/loading.vue'; // 关键功能：加载状态封装，检测中展示 Loading
import Snackbar from '../../components/snackbar.vue';
import request from '../../utils/request';

export default {
    components: {
        Dialog,
        Loading,
        Snackbar
    },
    data() {
        return {
            imagePreview: null,
            isDetecting: false,
            showReUploadDialog: false,
            showDetectionDialog: false,
            // 关键功能：统一页面级提示的显示状态与内容
            snackShow: false,
            snackType: 'error',
            snackContent: ''
        }
    },
    methods: {
        // 处理文件选择
        handleFileChange(event) {
            const file = event.target.files[0];
            if (file) {
                this.processImageFile(file);
            }
        },

        // 触发文件选择对话框
        triggerFileInput() {
            document.getElementById('fileInput').click();
        },

        // 处理拖拽上传
        handleDrop(event) {
            event.preventDefault();
            const file = event.dataTransfer.files[0];
            if (file && file.type.startsWith('image/')) {
                this.processImageFile(file);
            }
        },

        // 处理图片文件并生成预览
        processImageFile(file) {
            // 关键功能：前端大小校验，限制图片文件 ≤ 5MB，使用页面级 Snackbar 提示
            if (file.size > 5 * 1024 * 1024) {
                this.snackType = 'error'
                this.snackContent = '文件大小不能超过5MB'
                this.snackShow = true
                return;
            }

            // 生成图片预览
            const reader = new FileReader();
            reader.onload = (e) => {
                this.imagePreview = e.target.result;
            };
            reader.readAsDataURL(file);
        },

        // 预览图片
        previewImage() {
            if (this.imagePreview) {
                ImagePreview(this.imagePreview);
            }
        },

        // 重新上传图片
        reUploadImage() {
            // 清空预览并触发文件选择对话框
            this.imagePreview = null;
            this.showReUploadDialog = false;
            document.getElementById('fileInput').value = '';
            this.$nextTick(() => {
                document.getElementById('fileInput').click();
            });
        },

        // 开始检测
        async startDetection() {
            if (!this.imagePreview) {
                // 关键功能：未选择图片提示，使用页面级 Snackbar
                this.snackType = 'error'
                this.snackContent = '请先上传图片'
                this.snackShow = true
                return;
            }
            this.showDetectionDialog = false;
            this.isDetecting = true;

            try {
                // 将dataURL转换为blob进行上传
                const blob = await this.dataURLtoBlob(this.imagePreview);
                const formData = new FormData();
                formData.append('file', blob, 'image.jpg');

                // 调用AI检测接口
                // 关键功能：使用统一的上传封装，自动携带 Authorization
                // 关键功能：路由前缀由 VITE_API_URL 提供，此处不再重复 "/api" 前缀
                const resp = await request.upload('/ai-detection/detect', formData)

                if (resp && resp.success) {
                    const d = resp.data
                    this.$router.push({
                        path: '/main/detection-result',
                        query: {
                            originalImage: d.originalImage,
                            resultImage: d.resultImage,
                            ratio: d.ratio,
                            diagnosis: d.diagnosis,
                            historyId: d.id
                        }
                    })
                } else {
                    // 关键功能：后端不可用时，回退到本机 Flask 服务
                    const flaskUrl = (import.meta.env.VITE_FLASK_DETECT_URL) || 'http://127.0.0.1:8001/predict'
                    const altRes = await fetch(flaskUrl, { method: 'POST', body: formData })
                    if (!altRes.ok) throw new Error('检测服务暂时不可用')
                    const alt = await altRes.json()
                    if (!alt || !alt.image) throw new Error('检测服务暂时不可用')
                    this.$router.push({
                        path: '/main/detection-result',
                        query: {
                            originalImage: this.imagePreview,
                            resultImage: alt.image,
                            ratio: alt.ratio,
                            diagnosis: alt.diagnosis,
                            historyId: alt.id || undefined
                        }
                    })
                }
            } catch (error) {
                console.error('Detection error:', error);
                this.snackType = 'error';
                this.snackContent = error.message || '检测失败，请重试';
                this.snackShow = true;
            } finally {
                this.isDetecting = false;
            }
        },

        // 将dataURL转换为Blob
        dataURLtoBlob(dataURL) {
            return new Promise((resolve) => {
                const arr = dataURL.split(',');
                const mime = arr[0].match(/:(.*?);/)[1];
                const bstr = atob(arr[1]);
                let n = bstr.length;
                const u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                resolve(new Blob([u8arr], { type: mime }));
            });
        },
        // 返回首页
        backhome() {
            this.$router.push('/main/home');
        }
    }

}

</script>

<style scoped></style>
